<?php

/*
login_model : 登录控制模型
*/

class Login_model extends CI_Model
{

	public $error;
	private $user;

	function __construct()
	{
		parent::__construct();
		//载入模型
		$this->load->model('User_model');
		//载入库
		$this->load->library('Forbid_resubmit');
	}

	//检查登录用户
	public function check($logined=FALSE)
	{
		//载入库
		$this->load->library('form_validation');

		//载入本地语言文件
		$this->lang->load('form_validation','chinese');

		//验证已经登录的用户
		if ($logined)
		{
			if ($user = $this->User_model->get_user('check', '', $this->input->cookie('username'), $this->input->cookie('password')))
			{
				$cookies = array(
					'user_id'	=> $user['user_id'],
					'username'	=> $user['username'],
					'realname'	=> $user['realname'],
					'password'	=> $user['password'],
					'database'	=> $user['database'],
					'environment'=> $user['environment']
					);
				$this->set_cookie($cookies);
				$this->user = $cookies;
				return TRUE;
			}
			else
			{
				$this->error = $this->User_model->error;
				if ('CHECK_ERROR' == $this->error)
				{
					$this->error = '登录异常，请重新登录。';
				}
				else
				{
					$this->error = '系统错误！';
				}
			}
			return FALSE;
		}

		//判断是否是重复提交
		if (!$this->forbid_resubmit->judge_submit($this->input->post('rand')))
		{
			return FALSE;
		}

		//验证表单登录
		if (TRUE == $this->input->post('login'))
		{
			$this->form_validation->set_rules('username', '账户', 'trim|required|min_length[5]|max_length[20]|alpha_dash|xss_clean');
			$this->form_validation->set_rules('password', '密码', 'trim|required|xss_clean');
			if (TRUE == $this->form_validation->run())
			{
				if ($user = $this->User_model->get_user('login', '', $this->input->post('username'), $this->input->post('password')))
				{
					$cookies = array(
						'user_id'	=> $user['user_id'],
						'username'	=> $user['username'],
						'realname'	=> $user['realname'],
						'password'	=> $user['password'],
						'database'	=> $user['database'],
						'environment'=> $user['environment']
						);
					$this->set_cookie($cookies);
					$this->user = $cookies;
					return TRUE;
				}
				else
				{
					$this->error = $this->User_model->error;
					if ('LOGIN_ERROR' == $this->error)
					{
						$this->error = '账户名或密码错误，请重试。';
					}
					else
					{
						$this->error = '系统错误！';
					}
				}
			}
			else
			{
				$this->error = '输入的格式不正确';
			}
		}
		else
		{
			$this->error = '请先登录';
		}
		return FALSE;

	}

	//检查用户通过后，更新COOKIE
	private function set_cookie($data, $expire=180000, $secure=false)
	{
		foreach ($data as $k=>$v)
		{
			$cookie = array(
				'name'	=>	$k,
				'value'	=>	$v,
				'expire'	=>	$expire,
			);
			$this->input->set_cookie($cookie);
		}
	}

	//登出删除COOKIE
	public function logout()
	{
		$user = array(
			'user_id'	=> '',
			'username'	=> '',
			'realname'	=> '',
			'password'	=> '',
			'database'	=> ''
		);
		$this->set_cookie($user, -1800, false);
	}

	//返回用户信息
	public function user()
	{
		return $this->user;
	}

}